
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta charset="utf-8" />
    <title>18.5.3. Tasks and coroutines &#8212; Python 3.6.10 documentation</title>
    <link rel="stylesheet" href="../_static/pydoctheme.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    
    <script type="text/javascript" src="../_static/sidebar.js"></script>
    
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python 3.6.10 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="next" title="18.5.4. Transports and protocols (callback based API)" href="asyncio-protocol.html" />
    <link rel="prev" title="18.5.2. Event loops" href="asyncio-eventloops.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
    <link rel="canonical" href="https://docs.python.org/3/library/asyncio-task.html" />
    
    <script type="text/javascript" src="../_static/copybutton.js"></script>
    <script type="text/javascript" src="../_static/switchers.js"></script>
    
    
 

  </head><body>
  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="asyncio-protocol.html" title="18.5.4. Transports and protocols (callback based API)"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="asyncio-eventloops.html" title="18.5.2. Event loops"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <span class="language_switcher_placeholder">en</span>
          <span class="version_switcher_placeholder">3.6.10</span>
          <a href="../index.html">Documentation </a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" ><span class="section-number">18. </span>Interprocess Communication and Networking</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="asyncio.html" accesskey="U"><span class="section-number">18.5. </span><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O, event loop, coroutines and tasks</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>    

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body" role="main">
            
  <div class="section" id="tasks-and-coroutines">
<h1><span class="section-number">18.5.3. </span>Tasks and coroutines<a class="headerlink" href="#tasks-and-coroutines" title="Permalink to this headline">¶</a></h1>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.6/Lib/asyncio/tasks.py">Lib/asyncio/tasks.py</a></p>
<p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.6/Lib/asyncio/coroutines.py">Lib/asyncio/coroutines.py</a></p>
<div class="section" id="coroutines">
<span id="coroutine"></span><h2><span class="section-number">18.5.3.1. </span>Coroutines<a class="headerlink" href="#coroutines" title="Permalink to this headline">¶</a></h2>
<p>Coroutines used with <a class="reference internal" href="asyncio.html#module-asyncio" title="asyncio: Asynchronous I/O, event loop, coroutines and tasks."><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code></a> may be implemented using the
<a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> statement, or by using <a class="reference internal" href="../glossary.html#term-generator"><span class="xref std std-term">generators</span></a>.
The <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> type of coroutine was added in Python 3.5, and
is recommended if there is no need to support older Python versions.</p>
<p>Generator-based coroutines should be decorated with <a class="reference internal" href="#asyncio.coroutine" title="asyncio.coroutine"><code class="xref py py-func docutils literal notranslate"><span class="pre">&#64;asyncio.coroutine</span></code></a>, although this is not strictly enforced.
The decorator enables compatibility with <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> coroutines,
and also serves as documentation.  Generator-based
coroutines use the <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> syntax introduced in <span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0380"><strong>PEP 380</strong></a>,
instead of the original <code class="docutils literal notranslate"><span class="pre">yield</span></code> syntax.</p>
<p>The word “coroutine”, like the word “generator”, is used for two
different (though related) concepts:</p>
<ul class="simple">
<li><p>The function that defines a coroutine
(a function definition using <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> or
decorated with <code class="docutils literal notranslate"><span class="pre">&#64;asyncio.coroutine</span></code>).  If disambiguation is needed
we will call this a <em>coroutine function</em> (<a class="reference internal" href="#asyncio.iscoroutinefunction" title="asyncio.iscoroutinefunction"><code class="xref py py-func docutils literal notranslate"><span class="pre">iscoroutinefunction()</span></code></a>
returns <code class="docutils literal notranslate"><span class="pre">True</span></code>).</p></li>
<li><p>The object obtained by calling a coroutine function.  This object
represents a computation or an I/O operation (usually a combination)
that will complete eventually.  If disambiguation is needed we will
call it a <em>coroutine object</em> (<a class="reference internal" href="#asyncio.iscoroutine" title="asyncio.iscoroutine"><code class="xref py py-func docutils literal notranslate"><span class="pre">iscoroutine()</span></code></a> returns <code class="docutils literal notranslate"><span class="pre">True</span></code>).</p></li>
</ul>
<p>Things a coroutine can do:</p>
<ul class="simple">
<li><p><code class="docutils literal notranslate"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">await</span> <span class="pre">future</span></code> or <code class="docutils literal notranslate"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">yield</span> <span class="pre">from</span> <span class="pre">future</span></code> –
suspends the coroutine until the
future is done, then returns the future’s result, or raises an
exception, which will be propagated.  (If the future is cancelled,
it will raise a <code class="docutils literal notranslate"><span class="pre">CancelledError</span></code> exception.)  Note that tasks are
futures, and everything said about futures also applies to tasks.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">await</span> <span class="pre">coroutine</span></code> or <code class="docutils literal notranslate"><span class="pre">result</span> <span class="pre">=</span> <span class="pre">yield</span> <span class="pre">from</span> <span class="pre">coroutine</span></code> –
wait for another coroutine to
produce a result (or raise an exception, which will be propagated).
The <code class="docutils literal notranslate"><span class="pre">coroutine</span></code> expression must be a <em>call</em> to another coroutine.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">return</span> <span class="pre">expression</span></code> – produce a result to the coroutine that is
waiting for this one using <a class="reference internal" href="../reference/expressions.html#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> or <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code>.</p></li>
<li><p><code class="docutils literal notranslate"><span class="pre">raise</span> <span class="pre">exception</span></code> – raise an exception in the coroutine that is
waiting for this one using <a class="reference internal" href="../reference/expressions.html#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> or <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code>.</p></li>
</ul>
<p>Calling a coroutine does not start its code running –
the coroutine object returned by the call doesn’t do anything until you
schedule its execution.  There are two basic ways to start it running:
call <code class="docutils literal notranslate"><span class="pre">await</span> <span class="pre">coroutine</span></code> or <code class="docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span> <span class="pre">coroutine</span></code> from another coroutine
(assuming the other coroutine is already running!), or schedule its execution
using the <a class="reference internal" href="#asyncio.ensure_future" title="asyncio.ensure_future"><code class="xref py py-func docutils literal notranslate"><span class="pre">ensure_future()</span></code></a> function or the <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.create_task" title="asyncio.AbstractEventLoop.create_task"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AbstractEventLoop.create_task()</span></code></a>
method.</p>
<p>Coroutines (and tasks) can only run when the event loop is running.</p>
<dl class="function">
<dt id="asyncio.coroutine">
<code class="sig-prename descclassname">&#64;</code><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">coroutine</code><a class="headerlink" href="#asyncio.coroutine" title="Permalink to this definition">¶</a></dt>
<dd><p>Decorator to mark generator-based coroutines.  This enables
the generator use <code class="xref std std-keyword docutils literal notranslate"><span class="pre">yield</span> <span class="pre">from</span></code> to call <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span>
<span class="pre">def</span></code></a> coroutines, and also enables the generator to be called by
<a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> coroutines, for instance using an
<a class="reference internal" href="../reference/expressions.html#await"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">await</span></code></a> expression.</p>
<p>There is no need to decorate <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> coroutines themselves.</p>
<p>If the generator is not yielded from before it is destroyed, an error
message is logged. See <a class="reference internal" href="asyncio-dev.html#asyncio-coroutine-not-scheduled"><span class="std std-ref">Detect coroutines never scheduled</span></a>.</p>
</dd></dl>

<div class="admonition note">
<p class="admonition-title">Note</p>
<p>In this documentation, some methods are documented as coroutines,
even if they are plain Python functions returning a <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a>.
This is intentional to have a freedom of tweaking the implementation
of these functions in the future. If such a function is needed to be
used in a callback-style code, wrap its result with <a class="reference internal" href="#asyncio.ensure_future" title="asyncio.ensure_future"><code class="xref py py-func docutils literal notranslate"><span class="pre">ensure_future()</span></code></a>.</p>
</div>
<div class="section" id="example-hello-world-coroutine">
<span id="asyncio-hello-world-coroutine"></span><h3><span class="section-number">18.5.3.1.1. </span>Example: Hello World coroutine<a class="headerlink" href="#example-hello-world-coroutine" title="Permalink to this headline">¶</a></h3>
<p>Example of coroutine displaying <code class="docutils literal notranslate"><span class="pre">&quot;Hello</span> <span class="pre">World&quot;</span></code>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>

<span class="k">async</span> <span class="k">def</span> <span class="nf">hello_world</span><span class="p">():</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Hello World!&quot;</span><span class="p">)</span>

<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="c1"># Blocking call which returns when the hello_world() coroutine is done</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">hello_world</span><span class="p">())</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<p>The <a class="reference internal" href="asyncio-eventloop.html#asyncio-hello-world-callback"><span class="std std-ref">Hello World with call_soon()</span></a>
example uses the <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.call_soon" title="asyncio.AbstractEventLoop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AbstractEventLoop.call_soon()</span></code></a> method to schedule a
callback.</p>
</div>
</div>
<div class="section" id="example-coroutine-displaying-the-current-date">
<span id="asyncio-date-coroutine"></span><h3><span class="section-number">18.5.3.1.2. </span>Example: Coroutine displaying the current date<a class="headerlink" href="#example-coroutine-displaying-the-current-date" title="Permalink to this headline">¶</a></h3>
<p>Example of coroutine displaying the current date every second during 5 seconds
using the <a class="reference internal" href="#asyncio.sleep" title="asyncio.sleep"><code class="xref py py-meth docutils literal notranslate"><span class="pre">sleep()</span></code></a> function:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>
<span class="kn">import</span> <span class="nn">datetime</span>

<span class="k">async</span> <span class="k">def</span> <span class="nf">display_date</span><span class="p">(</span><span class="n">loop</span><span class="p">):</span>
    <span class="n">end_time</span> <span class="o">=</span> <span class="n">loop</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">+</span> <span class="mf">5.0</span>
    <span class="k">while</span> <span class="kc">True</span><span class="p">:</span>
        <span class="nb">print</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">())</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">loop</span><span class="o">.</span><span class="n">time</span><span class="p">()</span> <span class="o">+</span> <span class="mf">1.0</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="n">end_time</span><span class="p">:</span>
            <span class="k">break</span>
        <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>

<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="c1"># Blocking call which returns when the display_date() coroutine is done</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">display_date</span><span class="p">(</span><span class="n">loop</span><span class="p">))</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<p>The <a class="reference internal" href="asyncio-eventloop.html#asyncio-date-callback"><span class="std std-ref">display the current date with call_later()</span></a> example uses a callback with the
<a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.call_later" title="asyncio.AbstractEventLoop.call_later"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AbstractEventLoop.call_later()</span></code></a> method.</p>
</div>
</div>
<div class="section" id="example-chain-coroutines">
<h3><span class="section-number">18.5.3.1.3. </span>Example: Chain coroutines<a class="headerlink" href="#example-chain-coroutines" title="Permalink to this headline">¶</a></h3>
<p>Example chaining coroutines:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>

<span class="k">async</span> <span class="k">def</span> <span class="nf">compute</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Compute </span><span class="si">%s</span><span class="s2"> + </span><span class="si">%s</span><span class="s2"> ...&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">))</span>
    <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mf">1.0</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">x</span> <span class="o">+</span> <span class="n">y</span>

<span class="k">async</span> <span class="k">def</span> <span class="nf">print_sum</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
    <span class="n">result</span> <span class="o">=</span> <span class="k">await</span> <span class="n">compute</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;</span><span class="si">%s</span><span class="s2"> + </span><span class="si">%s</span><span class="s2"> = </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">result</span><span class="p">))</span>

<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">print_sum</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">))</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p><code class="docutils literal notranslate"><span class="pre">compute()</span></code> is chained to <code class="docutils literal notranslate"><span class="pre">print_sum()</span></code>: <code class="docutils literal notranslate"><span class="pre">print_sum()</span></code> coroutine waits
until <code class="docutils literal notranslate"><span class="pre">compute()</span></code> is completed before returning its result.</p>
<p>Sequence diagram of the example:</p>
<img alt="../_images/tulip_coro.png" class="align-center" src="../_images/tulip_coro.png" />
<p>The “Task” is created by the <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.run_until_complete" title="asyncio.AbstractEventLoop.run_until_complete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AbstractEventLoop.run_until_complete()</span></code></a> method
when it gets a coroutine object instead of a task.</p>
<p>The diagram shows the control flow, it does not describe exactly how things
work internally. For example, the sleep coroutine creates an internal future
which uses <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.call_later" title="asyncio.AbstractEventLoop.call_later"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AbstractEventLoop.call_later()</span></code></a> to wake up the task in 1 second.</p>
</div>
</div>
<div class="section" id="invalidstateerror">
<h2><span class="section-number">18.5.3.2. </span>InvalidStateError<a class="headerlink" href="#invalidstateerror" title="Permalink to this headline">¶</a></h2>
<dl class="exception">
<dt id="asyncio.InvalidStateError">
<em class="property">exception </em><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">InvalidStateError</code><a class="headerlink" href="#asyncio.InvalidStateError" title="Permalink to this definition">¶</a></dt>
<dd><p>The operation is not allowed in this state.</p>
</dd></dl>

</div>
<div class="section" id="timeouterror">
<h2><span class="section-number">18.5.3.3. </span>TimeoutError<a class="headerlink" href="#timeouterror" title="Permalink to this headline">¶</a></h2>
<dl class="exception">
<dt id="asyncio.TimeoutError">
<em class="property">exception </em><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">TimeoutError</code><a class="headerlink" href="#asyncio.TimeoutError" title="Permalink to this definition">¶</a></dt>
<dd><p>The operation exceeded the given deadline.</p>
</dd></dl>

<div class="admonition note">
<p class="admonition-title">Note</p>
<p>This exception is different from the builtin <a class="reference internal" href="exceptions.html#TimeoutError" title="TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">TimeoutError</span></code></a> exception!</p>
</div>
</div>
<div class="section" id="future">
<h2><span class="section-number">18.5.3.4. </span>Future<a class="headerlink" href="#future" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="asyncio.Future">
<em class="property">class </em><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">Future</code><span class="sig-paren">(</span><em class="sig-param">*</em>, <em class="sig-param">loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future" title="Permalink to this definition">¶</a></dt>
<dd><p>This class is <em>almost</em> compatible with <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Future</span></code></a>.</p>
<p>Differences:</p>
<ul class="simple">
<li><p><a class="reference internal" href="#asyncio.Future.result" title="asyncio.Future.result"><code class="xref py py-meth docutils literal notranslate"><span class="pre">result()</span></code></a> and <a class="reference internal" href="#asyncio.Future.exception" title="asyncio.Future.exception"><code class="xref py py-meth docutils literal notranslate"><span class="pre">exception()</span></code></a> do not take a timeout argument and
raise an exception when the future isn’t done yet.</p></li>
<li><p>Callbacks registered with <a class="reference internal" href="#asyncio.Future.add_done_callback" title="asyncio.Future.add_done_callback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_done_callback()</span></code></a> are always called
via the event loop’s <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.call_soon" title="asyncio.AbstractEventLoop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call_soon()</span></code></a>.</p></li>
<li><p>This class is not compatible with the <a class="reference internal" href="concurrent.futures.html#concurrent.futures.wait" title="concurrent.futures.wait"><code class="xref py py-func docutils literal notranslate"><span class="pre">wait()</span></code></a> and
<a class="reference internal" href="concurrent.futures.html#concurrent.futures.as_completed" title="concurrent.futures.as_completed"><code class="xref py py-func docutils literal notranslate"><span class="pre">as_completed()</span></code></a> functions in the
<a class="reference internal" href="concurrent.futures.html#module-concurrent.futures" title="concurrent.futures: Execute computations concurrently using threads or processes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">concurrent.futures</span></code></a> package.</p></li>
</ul>
<p>This class is <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><span class="std std-ref">not thread safe</span></a>.</p>
<dl class="method">
<dt id="asyncio.Future.cancel">
<code class="sig-name descname">cancel</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.cancel" title="Permalink to this definition">¶</a></dt>
<dd><p>Cancel the future and schedule callbacks.</p>
<p>If the future is already done or cancelled, return <code class="docutils literal notranslate"><span class="pre">False</span></code>. Otherwise,
change the future’s state to cancelled, schedule the callbacks and return
<code class="docutils literal notranslate"><span class="pre">True</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.cancelled">
<code class="sig-name descname">cancelled</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.cancelled" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the future was cancelled.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.done">
<code class="sig-name descname">done</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.done" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if the future is done.</p>
<p>Done means either that a result / exception are available, or that the
future was cancelled.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.result">
<code class="sig-name descname">result</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.result" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the result this future represents.</p>
<p>If the future has been cancelled, raises <code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code>. If the
future’s result isn’t yet available, raises <a class="reference internal" href="#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a>. If
the future is done and has an exception set, this exception is raised.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.exception">
<code class="sig-name descname">exception</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.exception" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the exception that was set on this future.</p>
<p>The exception (or <code class="docutils literal notranslate"><span class="pre">None</span></code> if no exception was set) is returned only if
the future is done. If the future has been cancelled, raises
<code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code>. If the future isn’t done yet, raises
<a class="reference internal" href="#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.add_done_callback">
<code class="sig-name descname">add_done_callback</code><span class="sig-paren">(</span><em class="sig-param">fn</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.add_done_callback" title="Permalink to this definition">¶</a></dt>
<dd><p>Add a callback to be run when the future becomes done.</p>
<p>The callback is called with a single argument - the future object. If the
future is already done when this is called, the callback is scheduled
with <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.call_soon" title="asyncio.AbstractEventLoop.call_soon"><code class="xref py py-meth docutils literal notranslate"><span class="pre">call_soon()</span></code></a>.</p>
<p><a class="reference internal" href="asyncio-eventloop.html#asyncio-pass-keywords"><span class="std std-ref">Use functools.partial to pass parameters to the callback</span></a>. For example,
<code class="docutils literal notranslate"><span class="pre">fut.add_done_callback(functools.partial(print,</span> <span class="pre">&quot;Future:&quot;,</span>
<span class="pre">flush=True))</span></code> will call <code class="docutils literal notranslate"><span class="pre">print(&quot;Future:&quot;,</span> <span class="pre">fut,</span> <span class="pre">flush=True)</span></code>.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.remove_done_callback">
<code class="sig-name descname">remove_done_callback</code><span class="sig-paren">(</span><em class="sig-param">fn</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.remove_done_callback" title="Permalink to this definition">¶</a></dt>
<dd><p>Remove all instances of a callback from the “call when done” list.</p>
<p>Returns the number of callbacks removed.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.set_result">
<code class="sig-name descname">set_result</code><span class="sig-paren">(</span><em class="sig-param">result</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.set_result" title="Permalink to this definition">¶</a></dt>
<dd><p>Mark the future done and set its result.</p>
<p>If the future is already done when this method is called, raises
<a class="reference internal" href="#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Future.set_exception">
<code class="sig-name descname">set_exception</code><span class="sig-paren">(</span><em class="sig-param">exception</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Future.set_exception" title="Permalink to this definition">¶</a></dt>
<dd><p>Mark the future done and set an exception.</p>
<p>If the future is already done when this method is called, raises
<a class="reference internal" href="#asyncio.InvalidStateError" title="asyncio.InvalidStateError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">InvalidStateError</span></code></a>.</p>
</dd></dl>

</dd></dl>

<div class="section" id="example-future-with-run-until-complete">
<h3><span class="section-number">18.5.3.4.1. </span>Example: Future with run_until_complete()<a class="headerlink" href="#example-future-with-run-until-complete" title="Permalink to this headline">¶</a></h3>
<p>Example combining a <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a> and a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine function</span></a>:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>

<span class="k">async</span> <span class="k">def</span> <span class="nf">slow_operation</span><span class="p">(</span><span class="n">future</span><span class="p">):</span>
    <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
    <span class="n">future</span><span class="o">.</span><span class="n">set_result</span><span class="p">(</span><span class="s1">&#39;Future is done!&#39;</span><span class="p">)</span>

<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="n">future</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Future</span><span class="p">()</span>
<span class="n">asyncio</span><span class="o">.</span><span class="n">ensure_future</span><span class="p">(</span><span class="n">slow_operation</span><span class="p">(</span><span class="n">future</span><span class="p">))</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">future</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">future</span><span class="o">.</span><span class="n">result</span><span class="p">())</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>The coroutine function is responsible for the computation (which takes 1 second)
and it stores the result into the future. The
<a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.run_until_complete" title="asyncio.AbstractEventLoop.run_until_complete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run_until_complete()</span></code></a> method waits for the completion of
the future.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.run_until_complete" title="asyncio.AbstractEventLoop.run_until_complete"><code class="xref py py-meth docutils literal notranslate"><span class="pre">run_until_complete()</span></code></a> method uses internally the
<a class="reference internal" href="#asyncio.Future.add_done_callback" title="asyncio.Future.add_done_callback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">add_done_callback()</span></code></a> method to be notified when the future is
done.</p>
</div>
</div>
<div class="section" id="example-future-with-run-forever">
<h3><span class="section-number">18.5.3.4.2. </span>Example: Future with run_forever()<a class="headerlink" href="#example-future-with-run-forever" title="Permalink to this headline">¶</a></h3>
<p>The previous example can be written differently using the
<a class="reference internal" href="#asyncio.Future.add_done_callback" title="asyncio.Future.add_done_callback"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Future.add_done_callback()</span></code></a> method to describe explicitly the control
flow:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>

<span class="k">async</span> <span class="k">def</span> <span class="nf">slow_operation</span><span class="p">(</span><span class="n">future</span><span class="p">):</span>
    <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
    <span class="n">future</span><span class="o">.</span><span class="n">set_result</span><span class="p">(</span><span class="s1">&#39;Future is done!&#39;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">got_result</span><span class="p">(</span><span class="n">future</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">future</span><span class="o">.</span><span class="n">result</span><span class="p">())</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">stop</span><span class="p">()</span>

<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="n">future</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">Future</span><span class="p">()</span>
<span class="n">asyncio</span><span class="o">.</span><span class="n">ensure_future</span><span class="p">(</span><span class="n">slow_operation</span><span class="p">(</span><span class="n">future</span><span class="p">))</span>
<span class="n">future</span><span class="o">.</span><span class="n">add_done_callback</span><span class="p">(</span><span class="n">got_result</span><span class="p">)</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">run_forever</span><span class="p">()</span>
<span class="k">finally</span><span class="p">:</span>
    <span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>In this example, the future is used to link <code class="docutils literal notranslate"><span class="pre">slow_operation()</span></code> to
<code class="docutils literal notranslate"><span class="pre">got_result()</span></code>: when <code class="docutils literal notranslate"><span class="pre">slow_operation()</span></code> is done, <code class="docutils literal notranslate"><span class="pre">got_result()</span></code> is called
with the result.</p>
</div>
</div>
<div class="section" id="task">
<h2><span class="section-number">18.5.3.5. </span>Task<a class="headerlink" href="#task" title="Permalink to this headline">¶</a></h2>
<dl class="class">
<dt id="asyncio.Task">
<em class="property">class </em><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">Task</code><span class="sig-paren">(</span><em class="sig-param">coro</em>, <em class="sig-param">*</em>, <em class="sig-param">loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task" title="Permalink to this definition">¶</a></dt>
<dd><p>Schedule the execution of a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a>: wrap it in a
future. A task is a subclass of <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a>.</p>
<p>A task is responsible for executing a coroutine object in an event loop.  If
the wrapped coroutine yields from a future, the task suspends the execution
of the wrapped coroutine and waits for the completion of the future. When
the future is done, the execution of the wrapped coroutine restarts with the
result or the exception of the future.</p>
<p>Event loops use cooperative scheduling: an event loop only runs one task at
a time. Other tasks may run in parallel if other event loops are
running in different threads. While a task waits for the completion of a
future, the event loop executes a new task.</p>
<p>The cancellation of a task is different from the cancelation of a
future. Calling <a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancel()</span></code></a> will throw a
<a class="reference internal" href="concurrent.futures.html#concurrent.futures.CancelledError" title="concurrent.futures.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> to the wrapped
coroutine. <a class="reference internal" href="#asyncio.Future.cancelled" title="asyncio.Future.cancelled"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancelled()</span></code></a> only returns <code class="docutils literal notranslate"><span class="pre">True</span></code> if the
wrapped coroutine did not catch the
<a class="reference internal" href="concurrent.futures.html#concurrent.futures.CancelledError" title="concurrent.futures.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> exception, or raised a
<a class="reference internal" href="concurrent.futures.html#concurrent.futures.CancelledError" title="concurrent.futures.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> exception.</p>
<p>If a pending task is destroyed, the execution of its wrapped <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a> did not complete. It is probably a bug and a warning is
logged: see <a class="reference internal" href="asyncio-dev.html#asyncio-pending-task-destroyed"><span class="std std-ref">Pending task destroyed</span></a>.</p>
<p>Don’t directly create <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> instances: use the <a class="reference internal" href="#asyncio.ensure_future" title="asyncio.ensure_future"><code class="xref py py-func docutils literal notranslate"><span class="pre">ensure_future()</span></code></a>
function or the <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.create_task" title="asyncio.AbstractEventLoop.create_task"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AbstractEventLoop.create_task()</span></code></a> method.</p>
<p>This class is <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><span class="std std-ref">not thread safe</span></a>.</p>
<dl class="method">
<dt id="asyncio.Task.all_tasks">
<em class="property">classmethod </em><code class="sig-name descname">all_tasks</code><span class="sig-paren">(</span><em class="sig-param">loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.all_tasks" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a set of all tasks for an event loop.</p>
<p>By default all tasks for the current event loop are returned.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Task.current_task">
<em class="property">classmethod </em><code class="sig-name descname">current_task</code><span class="sig-paren">(</span><em class="sig-param">loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.current_task" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the currently running task in an event loop or <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<p>By default the current task for the current event loop is returned.</p>
<p><code class="docutils literal notranslate"><span class="pre">None</span></code> is returned when called not in the context of a <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a>.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Task.cancel">
<code class="sig-name descname">cancel</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.cancel" title="Permalink to this definition">¶</a></dt>
<dd><p>Request that this task cancel itself.</p>
<p>This arranges for a <a class="reference internal" href="concurrent.futures.html#concurrent.futures.CancelledError" title="concurrent.futures.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> to be
thrown into the wrapped coroutine on the next cycle through the event
loop. The coroutine then has a chance to clean up or even deny the
request using try/except/finally.</p>
<p>Unlike <a class="reference internal" href="#asyncio.Future.cancel" title="asyncio.Future.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">Future.cancel()</span></code></a>, this does not guarantee that the task
will be cancelled: the exception might be caught and acted upon, delaying
cancellation of the task or preventing cancellation completely. The task
may also return a value or raise a different exception.</p>
<p>Immediately after this method is called, <a class="reference internal" href="#asyncio.Future.cancelled" title="asyncio.Future.cancelled"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancelled()</span></code></a> will
not return <code class="docutils literal notranslate"><span class="pre">True</span></code> (unless the task was already cancelled). A task will
be marked as cancelled when the wrapped coroutine terminates with a
<a class="reference internal" href="concurrent.futures.html#concurrent.futures.CancelledError" title="concurrent.futures.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> exception (even if
<a class="reference internal" href="#asyncio.Task.cancel" title="asyncio.Task.cancel"><code class="xref py py-meth docutils literal notranslate"><span class="pre">cancel()</span></code></a> was not called).</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Task.get_stack">
<code class="sig-name descname">get_stack</code><span class="sig-paren">(</span><em class="sig-param">*</em>, <em class="sig-param">limit=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.get_stack" title="Permalink to this definition">¶</a></dt>
<dd><p>Return the list of stack frames for this task’s coroutine.</p>
<p>If the coroutine is not done, this returns the stack where it is
suspended.  If the coroutine has completed successfully or was
cancelled, this returns an empty list.  If the coroutine was
terminated by an exception, this returns the list of traceback
frames.</p>
<p>The frames are always ordered from oldest to newest.</p>
<p>The optional limit gives the maximum number of frames to return; by
default all available frames are returned.  Its meaning differs depending
on whether a stack or a traceback is returned: the newest frames of a
stack are returned, but the oldest frames of a traceback are returned.
(This matches the behavior of the traceback module.)</p>
<p>For reasons beyond our control, only one stack frame is returned for a
suspended coroutine.</p>
</dd></dl>

<dl class="method">
<dt id="asyncio.Task.print_stack">
<code class="sig-name descname">print_stack</code><span class="sig-paren">(</span><em class="sig-param">*</em>, <em class="sig-param">limit=None</em>, <em class="sig-param">file=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.Task.print_stack" title="Permalink to this definition">¶</a></dt>
<dd><p>Print the stack or traceback for this task’s coroutine.</p>
<p>This produces output similar to that of the traceback module, for the
frames retrieved by get_stack().  The limit argument is passed to
get_stack().  The file argument is an I/O stream to which the output
is written; by default output is written to sys.stderr.</p>
</dd></dl>

</dd></dl>

<div class="section" id="example-parallel-execution-of-tasks">
<h3><span class="section-number">18.5.3.5.1. </span>Example: Parallel execution of tasks<a class="headerlink" href="#example-parallel-execution-of-tasks" title="Permalink to this headline">¶</a></h3>
<p>Example executing 3 tasks (A, B, C) in parallel:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">asyncio</span>

<span class="k">async</span> <span class="k">def</span> <span class="nf">factorial</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">number</span><span class="p">):</span>
    <span class="n">f</span> <span class="o">=</span> <span class="mi">1</span>
    <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="n">number</span><span class="o">+</span><span class="mi">1</span><span class="p">):</span>
        <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Task </span><span class="si">%s</span><span class="s2">: Compute factorial(</span><span class="si">%s</span><span class="s2">)...&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">i</span><span class="p">))</span>
        <span class="k">await</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
        <span class="n">f</span> <span class="o">*=</span> <span class="n">i</span>
    <span class="nb">print</span><span class="p">(</span><span class="s2">&quot;Task </span><span class="si">%s</span><span class="s2">: factorial(</span><span class="si">%s</span><span class="s2">) = </span><span class="si">%s</span><span class="s2">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">number</span><span class="p">,</span> <span class="n">f</span><span class="p">))</span>

<span class="n">loop</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">get_event_loop</span><span class="p">()</span>
<span class="n">loop</span><span class="o">.</span><span class="n">run_until_complete</span><span class="p">(</span><span class="n">asyncio</span><span class="o">.</span><span class="n">gather</span><span class="p">(</span>
    <span class="n">factorial</span><span class="p">(</span><span class="s2">&quot;A&quot;</span><span class="p">,</span> <span class="mi">2</span><span class="p">),</span>
    <span class="n">factorial</span><span class="p">(</span><span class="s2">&quot;B&quot;</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span>
    <span class="n">factorial</span><span class="p">(</span><span class="s2">&quot;C&quot;</span><span class="p">,</span> <span class="mi">4</span><span class="p">),</span>
<span class="p">))</span>
<span class="n">loop</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
</div>
<p>Output:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">Task</span> <span class="n">A</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">...</span>
<span class="n">Task</span> <span class="n">B</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">...</span>
<span class="n">Task</span> <span class="n">C</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span><span class="o">...</span>
<span class="n">Task</span> <span class="n">A</span><span class="p">:</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">2</span><span class="p">)</span> <span class="o">=</span> <span class="mi">2</span>
<span class="n">Task</span> <span class="n">B</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">...</span>
<span class="n">Task</span> <span class="n">C</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span><span class="o">...</span>
<span class="n">Task</span> <span class="n">B</span><span class="p">:</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">3</span><span class="p">)</span> <span class="o">=</span> <span class="mi">6</span>
<span class="n">Task</span> <span class="n">C</span><span class="p">:</span> <span class="n">Compute</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span><span class="o">...</span>
<span class="n">Task</span> <span class="n">C</span><span class="p">:</span> <span class="n">factorial</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span> <span class="o">=</span> <span class="mi">24</span>
</pre></div>
</div>
<p>A task is automatically scheduled for execution when it is created. The event
loop stops when all tasks are done.</p>
</div>
</div>
<div class="section" id="task-functions">
<h2><span class="section-number">18.5.3.6. </span>Task functions<a class="headerlink" href="#task-functions" title="Permalink to this headline">¶</a></h2>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>In the functions below, the optional <em>loop</em> argument allows explicitly setting
the event loop object used by the underlying task or coroutine.  If it’s
not provided, the default event loop is used.</p>
</div>
<dl class="function">
<dt id="asyncio.as_completed">
<code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">as_completed</code><span class="sig-paren">(</span><em class="sig-param">fs</em>, <em class="sig-param">*</em>, <em class="sig-param">loop=None</em>, <em class="sig-param">timeout=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.as_completed" title="Permalink to this definition">¶</a></dt>
<dd><p>Return an iterator whose values, when waited for, are <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a>
instances.</p>
<p>Raises <a class="reference internal" href="#asyncio.TimeoutError" title="asyncio.TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">asyncio.TimeoutError</span></code></a> if the timeout occurs before all Futures
are done.</p>
<p>Example:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="n">as_completed</span><span class="p">(</span><span class="n">fs</span><span class="p">):</span>
    <span class="n">result</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">f</span>  <span class="c1"># The &#39;yield from&#39; may raise</span>
    <span class="c1"># Use result</span>
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The futures <code class="docutils literal notranslate"><span class="pre">f</span></code> are not necessarily members of fs.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="asyncio.ensure_future">
<code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">ensure_future</code><span class="sig-paren">(</span><em class="sig-param">coro_or_future</em>, <em class="sig-param">*</em>, <em class="sig-param">loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.ensure_future" title="Permalink to this definition">¶</a></dt>
<dd><p>Schedule the execution of a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine object</span></a>: wrap it in
a future. Return a <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a> object.</p>
<p>If the argument is a <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a>, it is returned directly.</p>
<div class="versionadded">
<p><span class="versionmodified added">New in version 3.4.4.</span></p>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 3.5.1: </span>The function accepts any <a class="reference internal" href="../glossary.html#term-awaitable"><span class="xref std std-term">awaitable</span></a> object.</p>
</div>
<div class="admonition seealso">
<p class="admonition-title">See also</p>
<p>The <a class="reference internal" href="asyncio-eventloop.html#asyncio.AbstractEventLoop.create_task" title="asyncio.AbstractEventLoop.create_task"><code class="xref py py-meth docutils literal notranslate"><span class="pre">AbstractEventLoop.create_task()</span></code></a> method.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="asyncio.async">
<code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">async</code><span class="sig-paren">(</span><em class="sig-param">coro_or_future</em>, <em class="sig-param">*</em>, <em class="sig-param">loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.async" title="Permalink to this definition">¶</a></dt>
<dd><p>A deprecated alias to <a class="reference internal" href="#asyncio.ensure_future" title="asyncio.ensure_future"><code class="xref py py-func docutils literal notranslate"><span class="pre">ensure_future()</span></code></a>.</p>
<div class="deprecated">
<p><span class="versionmodified deprecated">Deprecated since version 3.4.4.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="asyncio.wrap_future">
<code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">wrap_future</code><span class="sig-paren">(</span><em class="sig-param">future</em>, <em class="sig-param">*</em>, <em class="sig-param">loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.wrap_future" title="Permalink to this definition">¶</a></dt>
<dd><p>Wrap a <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Future</span></code></a> object in a <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a>
object.</p>
</dd></dl>

<dl class="function">
<dt id="asyncio.gather">
<code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">gather</code><span class="sig-paren">(</span><em class="sig-param">*coros_or_futures</em>, <em class="sig-param">loop=None</em>, <em class="sig-param">return_exceptions=False</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.gather" title="Permalink to this definition">¶</a></dt>
<dd><p>Return a future aggregating results from the given coroutine objects or
futures.</p>
<p>All futures must share the same event loop.  If all the tasks are done
successfully, the returned future’s result is the list of results (in the
order of the original sequence, not necessarily the order of results
arrival).  If <em>return_exceptions</em> is true, exceptions in the tasks are
treated the same as successful results, and gathered in the result list;
otherwise, the first raised exception will be immediately propagated to the
returned future.</p>
<p>Cancellation: if the outer Future is cancelled, all children (that have not
completed yet) are also cancelled.  If any child is cancelled, this is
treated as if it raised <a class="reference internal" href="concurrent.futures.html#concurrent.futures.CancelledError" title="concurrent.futures.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a> – the
outer Future is <em>not</em> cancelled in this case.  (This is to prevent the
cancellation of one child to cause other children to be cancelled.)</p>
<div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 3.6.6: </span>If the <em>gather</em> itself is cancelled, the cancellation is propagated
regardless of <em>return_exceptions</em>.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="asyncio.iscoroutine">
<code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">iscoroutine</code><span class="sig-paren">(</span><em class="sig-param">obj</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.iscoroutine" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>obj</em> is a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine object</span></a>,
which may be based on a generator or an <a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> coroutine.</p>
</dd></dl>

<dl class="function">
<dt id="asyncio.iscoroutinefunction">
<code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">iscoroutinefunction</code><span class="sig-paren">(</span><em class="sig-param">func</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.iscoroutinefunction" title="Permalink to this definition">¶</a></dt>
<dd><p>Return <code class="docutils literal notranslate"><span class="pre">True</span></code> if <em>func</em> is determined to be a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine function</span></a>, which may be a decorated generator function or an
<a class="reference internal" href="../reference/compound_stmts.html#async-def"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">async</span> <span class="pre">def</span></code></a> function.</p>
</dd></dl>

<dl class="function">
<dt id="asyncio.run_coroutine_threadsafe">
<code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">run_coroutine_threadsafe</code><span class="sig-paren">(</span><em class="sig-param">coro</em>, <em class="sig-param">loop</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.run_coroutine_threadsafe" title="Permalink to this definition">¶</a></dt>
<dd><p>Submit a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine object</span></a> to a given event loop.</p>
<p>Return a <a class="reference internal" href="concurrent.futures.html#concurrent.futures.Future" title="concurrent.futures.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">concurrent.futures.Future</span></code></a> to access the result.</p>
<p>This function is meant to be called from a different thread than the one
where the event loop is running. Usage:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Create a coroutine</span>
<span class="n">coro</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">result</span><span class="o">=</span><span class="mi">3</span><span class="p">)</span>
<span class="c1"># Submit the coroutine to a given loop</span>
<span class="n">future</span> <span class="o">=</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">run_coroutine_threadsafe</span><span class="p">(</span><span class="n">coro</span><span class="p">,</span> <span class="n">loop</span><span class="p">)</span>
<span class="c1"># Wait for the result with an optional timeout argument</span>
<span class="k">assert</span> <span class="n">future</span><span class="o">.</span><span class="n">result</span><span class="p">(</span><span class="n">timeout</span><span class="p">)</span> <span class="o">==</span> <span class="mi">3</span>
</pre></div>
</div>
<p>If an exception is raised in the coroutine, the returned future will be
notified. It can also be used to cancel the task in the event loop:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="n">result</span> <span class="o">=</span> <span class="n">future</span><span class="o">.</span><span class="n">result</span><span class="p">(</span><span class="n">timeout</span><span class="p">)</span>
<span class="k">except</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">TimeoutError</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The coroutine took too long, cancelling the task...&#39;</span><span class="p">)</span>
    <span class="n">future</span><span class="o">.</span><span class="n">cancel</span><span class="p">()</span>
<span class="k">except</span> <span class="ne">Exception</span> <span class="k">as</span> <span class="n">exc</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The coroutine raised an exception: </span><span class="si">{!r}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">exc</span><span class="p">))</span>
<span class="k">else</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="s1">&#39;The coroutine returned: </span><span class="si">{!r}</span><span class="s1">&#39;</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">result</span><span class="p">))</span>
</pre></div>
</div>
<p>See the <a class="reference internal" href="asyncio-dev.html#asyncio-multithreading"><span class="std std-ref">concurrency and multithreading</span></a>
section of the documentation.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Unlike other functions from the module,
<a class="reference internal" href="#asyncio.run_coroutine_threadsafe" title="asyncio.run_coroutine_threadsafe"><code class="xref py py-func docutils literal notranslate"><span class="pre">run_coroutine_threadsafe()</span></code></a> requires the <em>loop</em> argument to
be passed explicitly.</p>
</div>
<div class="versionadded">
<p><span class="versionmodified added">New in version 3.5.1.</span></p>
</div>
</dd></dl>

<dl class="function">
<dt id="asyncio.sleep">
<em class="property">coroutine </em><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">sleep</code><span class="sig-paren">(</span><em class="sig-param">delay</em>, <em class="sig-param">result=None</em>, <em class="sig-param">*</em>, <em class="sig-param">loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.sleep" title="Permalink to this definition">¶</a></dt>
<dd><p>Create a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a> that completes after a given
time (in seconds).  If <em>result</em> is provided, it is produced to the caller
when the coroutine completes.</p>
<p>The resolution of the sleep depends on the <a class="reference internal" href="asyncio-eventloop.html#asyncio-delayed-calls"><span class="std std-ref">granularity of the event
loop</span></a>.</p>
<p>This function is a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a>.</p>
</dd></dl>

<dl class="function">
<dt id="asyncio.shield">
<em class="property">coroutine </em><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">shield</code><span class="sig-paren">(</span><em class="sig-param">arg</em>, <em class="sig-param">*</em>, <em class="sig-param">loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.shield" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait for a future, shielding it from cancellation.</p>
<p>The statement:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">res</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">shield</span><span class="p">(</span><span class="n">something</span><span class="p">())</span>
</pre></div>
</div>
<p>is exactly equivalent to the statement:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">res</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">something</span><span class="p">()</span>
</pre></div>
</div>
<p><em>except</em> that if the coroutine containing it is cancelled, the task running
in <code class="docutils literal notranslate"><span class="pre">something()</span></code> is not cancelled.  From the point of view of
<code class="docutils literal notranslate"><span class="pre">something()</span></code>, the cancellation did not happen.  But its caller is still
cancelled, so the yield-from expression still raises
<a class="reference internal" href="concurrent.futures.html#concurrent.futures.CancelledError" title="concurrent.futures.CancelledError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">CancelledError</span></code></a>.  Note: If <code class="docutils literal notranslate"><span class="pre">something()</span></code> is
cancelled by other means this will still cancel <code class="docutils literal notranslate"><span class="pre">shield()</span></code>.</p>
<p>If you want to completely ignore cancellation (not recommended) you can
combine <code class="docutils literal notranslate"><span class="pre">shield()</span></code> with a try/except clause, as follows:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="k">try</span><span class="p">:</span>
    <span class="n">res</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">shield</span><span class="p">(</span><span class="n">something</span><span class="p">())</span>
<span class="k">except</span> <span class="n">CancelledError</span><span class="p">:</span>
    <span class="n">res</span> <span class="o">=</span> <span class="kc">None</span>
</pre></div>
</div>
</dd></dl>

<dl class="function">
<dt id="asyncio.wait">
<em class="property">coroutine </em><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">wait</code><span class="sig-paren">(</span><em class="sig-param">futures</em>, <em class="sig-param">*</em>, <em class="sig-param">loop=None</em>, <em class="sig-param">timeout=None</em>, <em class="sig-param">return_when=ALL_COMPLETED</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.wait" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait for the Futures and coroutine objects given by the sequence <em>futures</em>
to complete.  Coroutines will be wrapped in Tasks. Returns two sets of
<a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a>: (done, pending).</p>
<p>The sequence <em>futures</em> must not be empty.</p>
<p><em>timeout</em> can be used to control the maximum number of seconds to wait before
returning.  <em>timeout</em> can be an int or float.  If <em>timeout</em> is not specified
or <code class="docutils literal notranslate"><span class="pre">None</span></code>, there is no limit to the wait time.</p>
<p><em>return_when</em> indicates when this function should return.  It must be one of
the following constants of the <a class="reference internal" href="concurrent.futures.html#module-concurrent.futures" title="concurrent.futures: Execute computations concurrently using threads or processes."><code class="xref py py-mod docutils literal notranslate"><span class="pre">concurrent.futures</span></code></a> module:</p>
<table class="docutils align-default">
<colgroup>
<col style="width: 42%" />
<col style="width: 58%" />
</colgroup>
<thead>
<tr class="row-odd"><th class="head"><p>Constant</p></th>
<th class="head"><p>Description</p></th>
</tr>
</thead>
<tbody>
<tr class="row-even"><td><p><code class="xref py py-const docutils literal notranslate"><span class="pre">FIRST_COMPLETED</span></code></p></td>
<td><p>The function will return when any
future finishes or is cancelled.</p></td>
</tr>
<tr class="row-odd"><td><p><code class="xref py py-const docutils literal notranslate"><span class="pre">FIRST_EXCEPTION</span></code></p></td>
<td><p>The function will return when any
future finishes by raising an
exception.  If no future raises an
exception then it is equivalent to
<code class="xref py py-const docutils literal notranslate"><span class="pre">ALL_COMPLETED</span></code>.</p></td>
</tr>
<tr class="row-even"><td><p><code class="xref py py-const docutils literal notranslate"><span class="pre">ALL_COMPLETED</span></code></p></td>
<td><p>The function will return when all
futures finish or are cancelled.</p></td>
</tr>
</tbody>
</table>
<p>This function is a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a>.</p>
<p>Usage:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">done</span><span class="p">,</span> <span class="n">pending</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">wait</span><span class="p">(</span><span class="n">fs</span><span class="p">)</span>
</pre></div>
</div>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>This does not raise <a class="reference internal" href="#asyncio.TimeoutError" title="asyncio.TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">asyncio.TimeoutError</span></code></a>! Futures that aren’t done
when the timeout occurs are returned in the second set.</p>
</div>
</dd></dl>

<dl class="function">
<dt id="asyncio.wait_for">
<em class="property">coroutine </em><code class="sig-prename descclassname">asyncio.</code><code class="sig-name descname">wait_for</code><span class="sig-paren">(</span><em class="sig-param">fut</em>, <em class="sig-param">timeout</em>, <em class="sig-param">*</em>, <em class="sig-param">loop=None</em><span class="sig-paren">)</span><a class="headerlink" href="#asyncio.wait_for" title="Permalink to this definition">¶</a></dt>
<dd><p>Wait for the single <a class="reference internal" href="#asyncio.Future" title="asyncio.Future"><code class="xref py py-class docutils literal notranslate"><span class="pre">Future</span></code></a> or <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine object</span></a>
to complete with timeout. If <em>timeout</em> is <code class="docutils literal notranslate"><span class="pre">None</span></code>, block until the future
completes.</p>
<p>Coroutine will be wrapped in <a class="reference internal" href="#asyncio.Task" title="asyncio.Task"><code class="xref py py-class docutils literal notranslate"><span class="pre">Task</span></code></a>.</p>
<p>Returns result of the Future or coroutine.  When a timeout occurs, it
cancels the task and raises <a class="reference internal" href="#asyncio.TimeoutError" title="asyncio.TimeoutError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">asyncio.TimeoutError</span></code></a>. To avoid the task
cancellation, wrap it in <a class="reference internal" href="#asyncio.shield" title="asyncio.shield"><code class="xref py py-func docutils literal notranslate"><span class="pre">shield()</span></code></a>.</p>
<p>If the wait is cancelled, the future <em>fut</em> is also cancelled.</p>
<p>This function is a <a class="reference internal" href="#coroutine"><span class="std std-ref">coroutine</span></a>, usage:</p>
<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="n">result</span> <span class="o">=</span> <span class="k">yield from</span> <span class="n">asyncio</span><span class="o">.</span><span class="n">wait_for</span><span class="p">(</span><span class="n">fut</span><span class="p">,</span> <span class="mf">60.0</span><span class="p">)</span>
</pre></div>
</div>
<div class="versionchanged">
<p><span class="versionmodified changed">Changed in version 3.4.3: </span>If the wait is cancelled, the future <em>fut</em> is now also cancelled.</p>
</div>
</dd></dl>

</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">18.5.3. Tasks and coroutines</a><ul>
<li><a class="reference internal" href="#coroutines">18.5.3.1. Coroutines</a><ul>
<li><a class="reference internal" href="#example-hello-world-coroutine">18.5.3.1.1. Example: Hello World coroutine</a></li>
<li><a class="reference internal" href="#example-coroutine-displaying-the-current-date">18.5.3.1.2. Example: Coroutine displaying the current date</a></li>
<li><a class="reference internal" href="#example-chain-coroutines">18.5.3.1.3. Example: Chain coroutines</a></li>
</ul>
</li>
<li><a class="reference internal" href="#invalidstateerror">18.5.3.2. InvalidStateError</a></li>
<li><a class="reference internal" href="#timeouterror">18.5.3.3. TimeoutError</a></li>
<li><a class="reference internal" href="#future">18.5.3.4. Future</a><ul>
<li><a class="reference internal" href="#example-future-with-run-until-complete">18.5.3.4.1. Example: Future with run_until_complete()</a></li>
<li><a class="reference internal" href="#example-future-with-run-forever">18.5.3.4.2. Example: Future with run_forever()</a></li>
</ul>
</li>
<li><a class="reference internal" href="#task">18.5.3.5. Task</a><ul>
<li><a class="reference internal" href="#example-parallel-execution-of-tasks">18.5.3.5.1. Example: Parallel execution of tasks</a></li>
</ul>
</li>
<li><a class="reference internal" href="#task-functions">18.5.3.6. Task functions</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="asyncio-eventloops.html"
                        title="previous chapter"><span class="section-number">18.5.2. </span>Event loops</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="asyncio-protocol.html"
                        title="next chapter"><span class="section-number">18.5.4. </span>Transports and protocols (callback based API)</a></p>
  <div role="note" aria-label="source link">
    <h3>This Page</h3>
    <ul class="this-page-menu">
      <li><a href="../bugs.html">Report a Bug</a></li>
      <li>
        <a href="https://github.com/python/cpython/blob/3.6/Doc/library/asyncio-task.rst"
            rel="nofollow">Show Source
        </a>
      </li>
    </ul>
  </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>  
    <div class="related" role="navigation" aria-label="related navigation">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="asyncio-protocol.html" title="18.5.4. Transports and protocols (callback based API)"
             >next</a> |</li>
        <li class="right" >
          <a href="asyncio-eventloops.html" title="18.5.2. Event loops"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="https://www.python.org/">Python</a> &#187;</li>
        <li>
          <span class="language_switcher_placeholder">en</span>
          <span class="version_switcher_placeholder">3.6.10</span>
          <a href="../index.html">Documentation </a> &#187;
        </li>

          <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> &#187;</li>
          <li class="nav-item nav-item-2"><a href="ipc.html" ><span class="section-number">18. </span>Interprocess Communication and Networking</a> &#187;</li>
          <li class="nav-item nav-item-3"><a href="asyncio.html" ><span class="section-number">18.5. </span><code class="xref py py-mod docutils literal notranslate"><span class="pre">asyncio</span></code> — Asynchronous I/O, event loop, coroutines and tasks</a> &#187;</li>
    <li class="right">
        

    <div class="inline-search" style="display: none" role="search">
        <form class="inline-search" action="../search.html" method="get">
          <input placeholder="Quick search" type="text" name="q" />
          <input type="submit" value="Go" />
          <input type="hidden" name="check_keywords" value="yes" />
          <input type="hidden" name="area" value="default" />
        </form>
    </div>
    <script type="text/javascript">$('.inline-search').show(0);</script>
         |
    </li>

      </ul>
    </div>  
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 2001-2020, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.
    <a href="https://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Apr 30, 2020.
    <a href="../bugs.html">Found a bug</a>?
    <br />
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 2.3.1.
    </div>

  </body>
</html>